package tw.asap.plus.ui.activity;

import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import tw.asap.plus.R;
import tw.asap.plus.common.ConstValue;
import tw.asap.plus.entity.request.OrderDetailRequest;
import tw.asap.plus.entity.response.OrderDetail;
import tw.asap.plus.entity.response.ResponseDataWrapper;
import tw.asap.plus.network.config.HRetrofitCreator;
import tw.asap.plus.network.service.OrderService;
import tw.asap.plus.ui.AsapBaseActivity;
import tw.asap.plus.ui.custom.AppBar;
import tw.asap.plus.ui.custom.SimpleGoodsItem;
import tw.asap.plus.utils.AppManager;
import tw.asap.plus.utils.T;
import tw.asap.plus.utils.Toaster;

/**
 * Created by Yax on 15/11/9.
 */
public class OrderDetailActivity extends AsapBaseActivity {


    @InjectView(R.id.appbar)
    AppBar appbar;
    @InjectView(R.id.icon_merchant)
    ImageView iconMerchant;
    @InjectView(R.id.line1)
    View line1;
    @InjectView(R.id.icon_delivery)
    ImageView iconDelivery;
    @InjectView(R.id.line2)
    View line2;
    @InjectView(R.id.icon_finish)
    ImageView iconFinish;
    @InjectView(R.id.msg_merchant)
    TextView msgMerchant;
    @InjectView(R.id.msg_delivery)
    TextView msgDelivery;
    @InjectView(R.id.msg_finish)
    TextView msgFinish;
    @InjectView(R.id.ll_goods_content)
    LinearLayout llGoodsContent;
    @InjectView(R.id.delivery_amt_actrul)
    TextView deliveryAmtActrul;
    @InjectView(R.id.goods_amt_num)
    TextView goodsAmtNum;
    @InjectView(R.id.coupon_amt_num)
    TextView couponAmtNum;
    @InjectView(R.id.sum_amt)
    TextView sumAmt;
    @InjectView(R.id.order_sn)
    TextView orderSn;
    @InjectView(R.id.pay_state)
    TextView payState;
    @InjectView(R.id.order_no)
    TextView orderNo;
    @InjectView(R.id.order_time)
    TextView orderTime;
    @InjectView(R.id.order_name)
    TextView orderName;
    @InjectView(R.id.order_mobile)
    TextView orderMobile;
    @InjectView(R.id.order_address)
    TextView orderAddress;
    @InjectView(R.id.order_delivery_info)
    TextView orderDeliveryInfo;
    @InjectView(R.id.bt_reminder)
    TextView btReminder;
    @InjectView(R.id.bt_cancel)
    TextView btCancel;

    String order_sn;

    String[] orderForm;
    @InjectView(R.id.layout_operate)
    RelativeLayout layoutOperate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_order_detail);
        ButterKnife.inject(this);
        orderForm = new String[]{getString(R.string.wait_merchant_confirm),
                getString(R.string.payed_wait_confirm),
                getString(R.string.order_confirmed),
                getString(R.string.in_delivery),
                getString(R.string.order_finished),
                getString(R.string.merchant_cancel_order),
                getString(R.string.merchant_cancel_order),
                getString(R.string.merchant_cancel_order),};
        order_sn = getIntent().getStringExtra("ORDER_SN");
        appbar.setLeftClickEvent(v -> {
            AppManager.getAppManager().finishAllTopActivity();
            MainActivity.RESUME_ACTION = 2;
        });

        getOrderDetail(order_sn);
    }

    private void fillData(OrderDetail data) {
        deliveryAmtActrul.setText("$".concat(getFormatAmt(data.getShipping_price())));
        couponAmtNum.setText("- $".concat(getFormatAmt(data.getOrder_coupon())));
        sumAmt.setText("$".concat(getFormatAmt(data.getPay_amount())));

        int orderStatus = Integer.parseInt(data.getOrder_status());
        if (orderStatus < 3 || orderStatus > 4) {
            iconMerchant.setSelected(true);
            msgMerchant.setText(orderForm[orderStatus]);
            msgMerchant.setSelected(true);

        } else if (orderStatus == 3) {
            msgMerchant.setSelected(true);
            iconMerchant.setSelected(true);
            iconDelivery.setSelected(true);
            msgDelivery.setSelected(true);
            msgDelivery.setText(orderForm[orderStatus]);
        } else if (orderStatus == 4) {
            msgMerchant.setSelected(true);
            iconMerchant.setSelected(true);
            iconDelivery.setSelected(true);
            msgDelivery.setSelected(true);
            iconFinish.setSelected(true);
            msgFinish.setSelected(true);
            msgFinish.setText(orderForm[orderStatus]);
        }
        if(orderStatus >3){
            layoutOperate.setVisibility(View.GONE);
        }

        orderSn.setText(data.getShop_name());
        payState.setText(data.getPay_status());
        orderNo.setText(data.getOrder_sn());
        orderTime.setText(data.getCreate_time());
        orderName.setText(data.getOrder_name());
        orderMobile.setText(data.getContact());
        orderAddress.setText(data.getOrder_addr());
        orderDeliveryInfo.setText(data.getShip_name());
        int goodsAmount = 0;
        for (OrderDetail.ItemsEntity itemsEntity : data.getItems()) {
            goodsAmount += (Integer.parseInt(itemsEntity.getNums()) * Integer.parseInt(itemsEntity.getPrice()));
            SimpleGoodsItem goodsItem = new SimpleGoodsItem(this);
            goodsItem.setItemEntity(itemsEntity);
            llGoodsContent.addView(goodsItem);
        }

        goodsAmtNum.setText("$".concat(getFormatAmt(String.valueOf(goodsAmount))));
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        AppManager.getAppManager().finishAllTopActivity();
        MainActivity.RESUME_ACTION = 2;
    }

    public String getFormatAmt(String amt) {
        String formatAmt = "";
        try {
            formatAmt = String.format("%d", Integer.parseInt(amt) / 100);
        } catch (Exception e) {
            T.e(e.toString());
        }
        return formatAmt;
    }

    @OnClick(R.id.bt_cancel)
    protected void cancelOrder() {
        AlertDialog.Builder builder = new AlertDialog.Builder(OrderDetailActivity.this);
        builder.setMessage(getString(R.string.confirm_cancel_order));
        builder.setTitle(getString(R.string.tips));
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> {

        });
        builder.setPositiveButton(R.string.yes, (dialog, which) -> {
            HRetrofitCreator creator = HRetrofitCreator.getInstance();
            Observable.create(new Observable.OnSubscribe<ResponseDataWrapper>() {
                @Override
                public void call(Subscriber<? super ResponseDataWrapper> subscriber) {
                    OrderService service = creator.getService(OrderService.class);
                    subscriber.onNext(service.cancelOrder(new OrderDetailRequest(order_sn)));
                    subscriber.onCompleted();
                }
            }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                    .subscribe(new Subscriber<ResponseDataWrapper>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(ResponseDataWrapper orderDetail) {
                            if (orderDetail.respcd.equals(ConstValue.RESPCD)) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(OrderDetailActivity.this);
                                builder.setMessage(getString(R.string.cancel_success));
                                builder.setPositiveButton("OK", (dialog, which) -> {
                                    AppManager.getAppManager().finishAllTopActivity();
                                    MainActivity.RESUME_ACTION = 2;
                                    MainActivity.REFRESH_ORDER_LIST = 1;
                                }).show();
                            } else {
                                Toaster.s(OrderDetailActivity.this, orderDetail.resperr);
                            }
                        }
                    });
        }).show();
    }

    @OnClick(R.id.bt_reminder)
    protected void reminderOrder() {
        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        Observable.create(new Observable.OnSubscribe<ResponseDataWrapper>() {
            @Override
            public void call(Subscriber<? super ResponseDataWrapper> subscriber) {
                OrderService service = creator.getService(OrderService.class);
                subscriber.onNext(service.reminderOrder(new OrderDetailRequest(order_sn)));
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseDataWrapper>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseDataWrapper orderDetail) {
                        if (orderDetail.respcd.equals(ConstValue.RESPCD)) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(OrderDetailActivity.this);
                            builder.setTitle(R.string.tips);
                            builder.setMessage(getString(R.string.reminder_order_success));
                            builder.setPositiveButton("OK", (dialog, which) -> {
                            }).show();
                        } else {
                            Toaster.s(OrderDetailActivity.this, orderDetail.resperr);
                        }
                    }
                });
    }

    private void getOrderDetail(String order_sn) {
        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        Observable.create(new Observable.OnSubscribe<ResponseDataWrapper<OrderDetail>>() {
            @Override
            public void call(Subscriber<? super ResponseDataWrapper<OrderDetail>> subscriber) {
                OrderService service = creator.getService(OrderService.class);
                subscriber.onNext(service.getOrderDetail(new OrderDetailRequest(order_sn)));
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseDataWrapper<OrderDetail>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseDataWrapper<OrderDetail> orderDetail) {
                        if (orderDetail.respcd.equals(ConstValue.RESPCD)) {
                            fillData(orderDetail.data);
                        } else {
                            Toaster.s(OrderDetailActivity.this, orderDetail.resperr);
                        }
                    }
                });
    }


}
